/*
 * @Author: taosong 2289713738@qq.com
 * @Date: 2024-03-25 15:47:58
 * @LastEditors: taosong 2289713738@qq.com
 * @LastEditTime: 2024-03-25 18:16:16
 * @FilePath: \Song-ui\src\components\DropDown\DropDown.tsx
 * @Description:
 *
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved.
 */
import { Fragment, computed, defineComponent, ref } from 'vue'
import type { PropType } from 'vue'
import { type Placement, type Options } from '@popperjs/core'
import type { MenuOption } from './type'
import type { TooltipInstance } from '../Tooltip/type'
import Tooltip from '../Tooltip/Tooltip.vue'

export default defineComponent({
  name: 'SgDropdown',
  props: {
    placement: {
      type: String as PropType<Placement>,
      default: 'bottom'
    },
    trigger: {
      type: String as PropType<'click' | 'hover'>,
      default: 'hover'
    },
    transition: {
      type: String,
      default: 'fade'
    },
    openDelay: {
      type: Number,
      default: 0
    },
    closeDelay: {
      type: Number,
      default: 0
    },
    propperOptions: {
      type: Object as PropType<Options>
    },
    menuOptions: {
      type: Array as PropType<MenuOption[]>,
      required: true
    },
    hideAfterClick: {
      type: Boolean,
      default: true
    }
  },

  emits: ['visible-change', 'select'],

  setup(props, { slots, emit, expose }) {
    const tooltipRef = ref<TooltipInstance | null>(null)

    const itemClick = (e: MenuOption) => {
      if (e.disabled) {
        return
      }
    
      emit('select', e)
      
      if (props.hideAfterClick) {
        // 关闭
        tooltipRef.value?.hide()
      }
    }

    const visibleChange = (e: boolean) => {
      emit('visible-change', e)
    }

    // 导出实例
    expose({
      show: () => tooltipRef.value?.show(),
      hide: () => tooltipRef.value?.hide()
    })

    const options = computed(() => {
      return props.menuOptions.map((item) => {
        return (
          <Fragment key={item.key}>
            {item.divided ? <li role="sparator" class="divided-placeholder" /> : ''}
            <li
              class={{
                'sg-dropdown__item': true,
                'is-disabled': item.disabled,
                'is-divided': item.divided
              }}
              id={`dropdown-item-${item.key}`}
              onClick={() => itemClick(item)}
            >
              {item.label}
            </li>
          </Fragment>
        )
      })
    })

    return () => (
      <div class="sg-dropdown">
        <Tooltip
          placement={props.placement}
          trigger={props.trigger}
          propperOptions={props.propperOptions}
          ref={tooltipRef}
          onVisible-change={visibleChange}
        >
          {{
            default: () => slots.default && slots.default(),
            content: () => <ul class="sg-dropdown__menu">{options.value}</ul>
          }}
        </Tooltip>
      </div>
    )
  }
})
